package net.wicp.tams.common.micro.metric;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.springframework.context.annotation.Configuration;

import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.metrics.core.JsonReporter;
import net.wicp.tams.common.metrics.utility.TsLogger;

@Configuration
@EnableMetrics(proxyTargetClass = true, exposeProxy = true)
public class SpringConfiguringClass extends MetricsConfigurerAdapter {

	@Override
	public void configureReporters(MetricRegistry metricRegistry) {
		final JsonReporter.Builder reporter = JsonReporter.forRegistry(metricRegistry);
		reporter.outputTo(TsLogger.getTamsLogger())
				.filter(metricFilterPattern(Conf.get("common.micro.metric.filter.pattern")));
		registerReporter(reporter.build()).start(1, TimeUnit.MINUTES);
	}

	protected MetricFilter metricFilterPattern(final String pattern) {
		final Pattern filter = Pattern.compile(pattern);
		return new MetricFilter() {

			@Override
			public boolean matches(String name, Metric metric) {
				if (StringUtil.isNull(pattern) || "none".equals(pattern)) {
					return true;
				}
				return filter.matcher(name).matches();
			}

			@Override
			public String toString() {
				return "[MetricFilter regex="
						+ ((StringUtil.isNull(pattern) || "none".equals(pattern)) ? "all" : filter.pattern()) + "]";
			}

		};
	}

}